package org.example.common;

import cn.hutool.json.JSONObject;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.web.servlet.error.DefaultErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
public class ErrorController extends BasicErrorController {
    public  ErrorController(){
        super(new DefaultErrorAttributes(),new ErrorProperties());
    }
    @Override
    @RequestMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
    public ResponseEntity<Map<String,Object>> error(HttpServletRequest request){
        Map<String,Object> map =getErrorAttributes(request,isIncludeStackTrace(request,MediaType.ALL));
        HttpStatus status =getStatus(request);
        JSONObject result = new JSONObject();
        result.put("code",status.value());
        result.put("msg",map.get("message"));
        return new ResponseEntity(result.toString(),status);
    }
}
